<script setup lang="ts" name="MarkdownEditor">
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { onMountedOrActivated } from '@/hooks/web/useOnMountedOrActivated'
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useLocaleStoreWithOut } from '@/store/modules/locale'

const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)
const localeStore = useLocaleStoreWithOut()
const { currentLocale } = storeToRefs(localeStore)
const { t } = useI18n() // 国际化
const { VITE_BASE_API_PATH, VITE_PUBLIC_PATH } = import.meta.env

const getTheme = (
  isLight: boolean,
  themeMode: 'default' | 'content' | 'code' = 'default'
) => {
  const isDark = !isLight
  switch (themeMode) {
    case 'default':
      return isDark ? 'dark' : 'classic'
    case 'content':
      return isDark ? 'dark' : 'light'
    case 'code':
      return isDark ? 'dracula' : 'github'
  }
}

const props = defineProps({
  height: { type: Number, default: 360 },
  value: { type: String, default: '' }
})
const emits = defineEmits(['change', 'get', 'update:value'])

const valueRef = ref(props.value || '')

const vditor: any = ref(null)
watch(
  () => systemConfig.value.isLight,
  (val) => {
    vditor.value.setTheme(getTheme(val) as any, getTheme(val, 'content'), getTheme(val, 'code'))
  }
)
watch(
  () => currentLocale.value.markdownLocale,
  () => {
    destroy()
    initVditor()
  }
)

watch(
  () => props.value,
  (v) => {
    if (v !== valueRef.value) {
      vditor.value.setValue(v)
    }
    valueRef.value = v
  }
)

const initVditor = () => {
  const bindValue = { ...props }
  vditor.value = new Vditor('vditor', {
    cdn: VITE_PUBLIC_PATH + 'vditor',
    theme: getTheme(systemConfig.value.isLight) as any,
    lang: currentLocale.value.markdownLocale,
    mode: 'sv',
    minHeight: 500,
    fullscreen: {
      index: 2048
    },
    preview: {
      theme: {
        // 设置内容主题
        current: getTheme(systemConfig.value.isLight, 'content')
      },
      actions: [],
      hljs: {
        style: getTheme(systemConfig.value.isLight, 'code'),
        lineNumber: true
      }
    },
    counter: {
      enable: true
    },
    icon: 'ant',
    toolbar: [
      'undo',
      'redo',
      '|',
      'headings',
      'bold',
      'italic',
      'strike',
      'link',
      '|',
      'list',
      'ordered-list',
      'check',
      'outdent',
      'indent',
      '|',
      'quote',
      'line',
      'code',
      'inline-code',
      'insert-before',
      'insert-after',
      'emoji',
      '|',
      {
        name: 'custom-upload',
        tip: '上传文件',
        className: 'vditor-toolbar__icon my-upload-icon',
        icon: `<svg viewBox="0 0 24 24" width="16" height="16">
                <path fill="currentColor" d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zm4 18H6V4h7v5h5v11z"/>
                <path fill="currentColor" d="M16 13h-3V10h-2v3H8l4 4 4-4z"/>
              </svg>`,
        click: () => {
          // 触发隐藏的 file input 选择文件
          const fileInput = document.createElement('input')
          fileInput.type = 'file'
          fileInput.multiple = true  // 允许多选
          fileInput.accept = 'image/*, .pdf' // 限制文件类型
          fileInput.onchange = (e) => {
            console.log(e)
            if (e.target && e.target.files) {
              handleFileUpload(e.target.files)
            }
          }
          fileInput.click()
        }
      },
      'table',
      '|',
      'fullscreen',
      'edit-mode',
      'export',
      'preview',
      'help'
      // {
      //   name: 'more',
      //   toolbar: [
      //     // 'both',
      //     // 'code-theme',
      //     // 'content-theme',
      //     'export',
      //     'outline',
      //     'preview',
      //     // 'devtools',
      //     // 'info',
      //     'help'
      //   ]
      // }
    ],
    input: (v) => {
      valueRef.value = v
      emits('update:value', v)
      emits('change', v)
    },
    after: () => {
      vditor.value.setValue(valueRef.value)
    },
    blur: () => {
      // unref(vditorRef)?.setValue(props.value);
    },
    ...bindValue,
    cache: {
      enable: false
    }
  })
}

const handleFileUpload = (files) => {
  console.log(files)
  // vditor.insertValue(`![](${url})`)
}

function destroy() {
  if (!vditor.value) return
  try {
    vditor.value?.destroy?.()
  } catch (error) {
    console.log(error)
  }
  vditor.value = null
}

onMountedOrActivated(initVditor, destroy)
</script>

<template>
  <div id="vditor" />
</template>
